package de.wbh.gwt.form.layouter.java.server.servlet.rpc;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import com.google.common.base.Charsets;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
import com.google.gwt.rpc.server.RpcServlet;

import de.wbh.gwt.form.layouter.gwt.rpc.ConfigurationService;
import de.wbh.gwt.form.layouter.java.server.ConfigurationHelper;
import de.wbh.gwt.form.layouter.shared.Configuration;

public class ConfigurationServiceImpl extends RpcServlet implements ConfigurationService {

	private static String dir = ConfigurationHelper.getInstance().getHomeDirectory();

	@Override
	public void createConf(String name, String efdName, String pdfName) {

		File path = new File(dir + "\\conf");

		if (!path.exists()) {
			path.mkdirs();
		}

		File f = new File(path, name + ".conf");
		try {
			Files.write(efdName + "," + pdfName, f, Charsets.UTF_8);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	@Override
	public Configuration getConf(String name) {
		File f = new File(dir + "\\conf\\" + name + ".conf");
		try {
			Iterator<String> parts = Splitter.on(",").split(Files.toString(f, Charsets.UTF_8)).iterator();
			Configuration configuration = new Configuration();
			configuration.name = name;
			configuration.efdName = parts.next();
			configuration.pdfName = parts.next();
			return configuration;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public List<String> getConfs() {
		File path = new File(dir + "\\conf");
		if (!path.exists()) {
			path.mkdirs();
		}
		File[] files = path.listFiles();
		List<String> confNames = Lists.newArrayList();
		for (File f : files) {
			confNames.add(f.getName().substring(0, f.getName().lastIndexOf(".")));
		}
		return confNames;
	}

}
